<template>
  <el-dialog
    title="编辑链接"
    :visible.sync="visible"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="linkForm" :model="linkForm" :rules="linkRules" label-width="100px">
      <!-- InnerLink搜索 -->
      <el-form-item label="内链搜索">
        <el-autocomplete
          v-model="searchQuery"
          :fetch-suggestions="searchInnerLinks"
          :debounce="300"
          placeholder="搜索内链或输入关键词"
          size="small"
          style="width: 100%;"
          :trigger-on-focus="false"
          @select="selectInnerLink"
        >
          <template slot-scope="{ item }">
            <div class="inner-link-item">
              <div class="link-title">{{ item.title }}</div>
              <div class="link-url">{{ item.url }}</div>
              <div class="link-meta">{{ item.type }} • 匹配度: {{ item.score }}%</div>
            </div>
          </template>
          <template slot="prepend">
            <i class="el-icon-search" />
          </template>
        </el-autocomplete>
      </el-form-item>

      <el-form-item label="链接文本" prop="text">
        <el-input
          v-model="linkForm.text"
          placeholder="显示的文本"
          size="small"
        />
      </el-form-item>

      <el-form-item label="链接地址" prop="href">
        <el-input
          v-model="linkForm.href"
          placeholder="https://example.com"
          size="small"
        >
          <template slot="prepend">🔗</template>
        </el-input>
      </el-form-item>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="打开方式">
            <el-select v-model="linkForm.target" size="small" style="width: 100%;">
              <el-option label="当前窗口" value="" />
              <el-option label="新窗口" value="_blank" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="链接属性">
            <el-select
              v-model="linkAttributeOptions"
              multiple
              collapse-tags
              size="small"
              style="width: 100%;"
              placeholder="选择属性"
            >
              <el-option label="NoFollow" value="nofollow" />
              <el-option label="Sponsored" value="sponsored" />
              <el-option label="UGC" value="ugc" />
              <el-option label="NoOpener" value="noopener" />
              <el-option label="NoReferrer" value="noreferrer" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="标题提示">
            <el-input
              v-model="linkForm.title"
              placeholder="鼠标悬停提示"
              size="small"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="CSS类名">
            <el-input
              v-model="linkForm.class"
              placeholder="自定义类名"
              size="small"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button v-if="isEditMode" type="danger" size="small" @click="removeLink">
        <i class="el-icon-delete" /> 删除链接
      </el-button>
      <el-button type="primary" size="small" @click="handleConfirm">
        <i class="el-icon-check" /> {{ isEditMode ? '更新' : '插入' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { Get as GetInnerLinks } from '@/api/cms/cmsm'
import qs from 'qs'

export default {
  name: 'LinkEditDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    editor: {
      type: Object,
      default: null
    },
    currentLink: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      linkForm: {
        text: '',
        href: '',
        target: '',
        title: '',
        class: ''
      },
      linkAttributeOptions: [],
      searchQuery: '',
      innerLinks: [],
      isSearching: false,
      linkRules: {
        href: [
          { required: true, message: '请输入链接地址', trigger: 'blur' },
          {
            pattern: /^(https?:\/\/|mailto:|tel:|#)/,
            message: '请输入有效的链接地址',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    isEditMode() {
      return this.currentLink && this.currentLink.href
    },
    relValue() {
      // 根据选中的选项生成rel属性值
      return this.linkAttributeOptions.filter(option =>
        ['nofollow', 'sponsored', 'ugc', 'noopener', 'noreferrer'].includes(option)
      ).join(' ').trim()
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.initForm()
      }
    },
    currentLink: {
      handler() {
        if (this.visible) {
          this.initForm()
        }
      },
      deep: true
    }
  },
  methods: {
    initForm() {
      if (this.currentLink && this.currentLink.href) {
        // 编辑模式
        this.linkForm = {
          text: this.getSelectedText(),
          href: this.currentLink.href || '',
          target: this.currentLink.target || '',
          title: this.currentLink.title || '',
          class: this.currentLink.class || ''
        }

        // 解析rel属性
        const rel = this.currentLink.rel || ''
        this.linkAttributeOptions = []
        if (rel.includes('nofollow')) this.linkAttributeOptions.push('nofollow')
        if (rel.includes('sponsored')) this.linkAttributeOptions.push('sponsored')
        if (rel.includes('ugc')) this.linkAttributeOptions.push('ugc')
        if (rel.includes('noopener')) this.linkAttributeOptions.push('noopener')
        if (rel.includes('noreferrer')) this.linkAttributeOptions.push('noreferrer')
      } else {
        // 新增模式
        this.linkForm = {
          text: this.getSelectedText(),
          href: '',
          target: '',
          title: '',
          class: ''
        }
        this.linkAttributeOptions = []
        this.searchQuery = ''
      }

      // 初始化时根据选中文本自动搜索
      this.$nextTick(() => {
        if (this.linkForm.text && !this.isEditMode) {
          this.searchQuery = this.linkForm.text
          this.searchInnerLinks(this.linkForm.text, (results) => {
            // 自动搜索结果供参考
          })
        }
      })
    },

    async searchInnerLinks(queryString, callback) {
      if (!queryString || queryString.length < 1) {
        callback([])
        return
      }

      this.isSearching = true
      try {
        // 调用真实的InnerLink API，需要指定table_name
        const response = await GetInnerLinks(null, qs.stringify({
          table_name: 'InnerLink',
          kw: queryString,
          pagesize: 20,
          page: 1
        }))

        if (response.data && response.data.data) {
          // 转换后端数据格式
          const results = response.data.data.map(item => ({
            id: item.id,
            title: item.keyword,
            url: item.link,
            type: item.is_nofollow ? 'NoFollow' : 'DoFollow',
            is_nofollow: item.is_nofollow,
            root_domain: item.root_domain,
            score: this.calculateRelevanceScore(queryString, item),
            value: `${item.keyword} - ${item.link}`
          }))
            .sort((a, b) => b.score - a.score)
            .slice(0, 10)

          callback(results)
        } else {
          callback([])
        }
      } catch (error) {
        console.error('内链搜索失败:', error)
        callback([])
      } finally {
        this.isSearching = false
      }
    },

    calculateRelevanceScore(query, item) {
      const queryLower = query.toLowerCase()
      const keywordLower = item.keyword.toLowerCase()
      const linkLower = item.link.toLowerCase()

      let score = 0

      // 精确匹配关键词
      if (keywordLower === queryLower) {
        score += 100
      } else if (keywordLower.includes(queryLower)) {
        score += 80
      }

      // 链接匹配
      if (linkLower.includes(queryLower)) {
        score += 50
      }

      // 模糊匹配
      if (this.fuzzyMatch(queryLower, keywordLower)) {
        score += 30
      }

      return Math.min(100, score)
    },

    fuzzyMatch(query, text) {
      const queryChars = query.split('')
      let textIndex = 0

      for (const char of queryChars) {
        const foundIndex = text.indexOf(char, textIndex)
        if (foundIndex === -1) return false
        textIndex = foundIndex + 1
      }

      return true
    },

    selectInnerLink(item) {
      this.linkForm.href = item.url
      this.linkForm.title = item.title
      if (!this.linkForm.text) {
        this.linkForm.text = item.title
      }

      // 根据内链设置自动配置属性
      if (item.is_nofollow && !this.linkAttributeOptions.includes('nofollow')) {
        this.linkAttributeOptions.push('nofollow')
      }

      // 如果是外链，自动设置新窗口打开
      if (item.url.startsWith('http') && !item.url.includes(window.location.hostname)) {
        this.linkForm.target = '_blank'
        if (!this.linkAttributeOptions.includes('noopener')) {
          this.linkAttributeOptions.push('noopener')
        }
      }

      this.searchQuery = `${item.title} - ${item.url}`
      this.$message.success(`已选择内链: ${item.title}`)
    },

    getSelectedText() {
      if (!this.editor) return ''
      const { selection } = this.editor.state
      return this.editor.state.doc.textBetween(selection.from, selection.to)
    },

    handleConfirm() {
      this.$refs.linkForm.validate(valid => {
        if (valid) {
          const attributes = {
            href: this.linkForm.href,
            target: this.linkForm.target || null,
            title: this.linkForm.title || null,
            class: this.linkForm.class || null,
            rel: this.relValue || null
          }

          // 清理空值
          Object.keys(attributes).forEach(key => {
            if (!attributes[key]) {
              delete attributes[key]
            }
          })

          if (this.linkForm.text && this.linkForm.text !== this.getSelectedText()) {
            // 如果修改了文本，先插入文本再设置链接
            this.editor.chain().focus()
              .insertContent(this.linkForm.text)
              .setTextSelection({ from: this.editor.state.selection.from - this.linkForm.text.length, to: this.editor.state.selection.from })
              .setLink(attributes)
              .run()
          } else {
            // 只设置链接属性
            this.editor.chain().focus().setLink(attributes).run()
          }

          this.$emit('update:visible', false)
          this.$message.success(this.isEditMode ? '链接更新成功' : '链接插入成功')
        }
      })
    },

    removeLink() {
      if (this.editor) {
        this.editor.chain().focus().unsetLink().run()
        this.$emit('update:visible', false)
        this.$message.success('链接已删除')
      }
    },

    handleClose() {
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.inner-link-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.inner-link-item:last-child {
  border-bottom: none;
}

.link-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.link-url {
  font-size: 12px;
  color: #409eff;
  margin-bottom: 2px;
  font-family: monospace;
}

.link-meta {
  font-size: 11px;
  color: #999;
}

::v-deep .el-autocomplete-suggestion__list {
  max-height: 200px;
  overflow-y: auto;
}

::v-deep .el-autocomplete-suggestion__wrap {
  max-height: 200px;
}
</style>
